#!/bin/bash

# BLAST数据库自动构建脚本
# 功能：从MySQL数据库导出蛋白质序列并构建BLAST数据库

set -e  # 遇到错误立即退出

# ============ 配置参数 ============
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
BLAST_DB_DIR="$PROJECT_ROOT/../blast_db"
LOG_FILE="$BLAST_DB_DIR/build_blast.log"

# 数据库连接信息
DB_USER="bioinfo_user"
DB_PASS="bioinfo_pass"
DB_NAME="bioinfo"
DB_HOST="localhost"

# ============ 函数定义 ============
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

error_exit() {
    log "ERROR: $1"
    exit 1
}

# ============ 主流程 ============
log "========== 开始构建BLAST数据库 =========="

# 1. 创建目录
log "创建BLAST数据库目录..."
mkdir -p "$BLAST_DB_DIR"
cd "$BLAST_DB_DIR"

# 2. 检查BLAST是否安装
if ! command -v blastp &> /dev/null; then
    error_exit "BLAST未安装，请先安装：sudo apt-get install ncbi-blast+"
fi

log "BLAST版本: $(blastp -version | head -1)"

# 3. 从MySQL导出蛋白质序列
log "从数据库导出蛋白质序列..."
mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" <<EOF > proteins_temp.txt
SELECT 
    CONCAT('>', accession, ' [', species, '] ', type, ' | ', assembly) as header,
    protein_sequence
FROM proteins
WHERE protein_sequence IS NOT NULL 
  AND protein_sequence != ''
  AND LENGTH(protein_sequence) > 0
ORDER BY id;
EOF

if [ ! -s proteins_temp.txt ]; then
    error_exit "导出序列失败或数据库为空"
fi

# 4. 转换为FASTA格式
log "转换为FASTA格式..."
awk 'NR%2==1{print $0} NR%2==0{print $0}' proteins_temp.txt | \
    sed 's/\t/\n/g' > proteins.fasta

# 统计序列数量
SEQ_COUNT=$(grep -c "^>" proteins.fasta)
log "导出 $SEQ_COUNT 条蛋白质序列"

if [ "$SEQ_COUNT" -eq 0 ]; then
    error_exit "未找到有效的蛋白质序列"
fi

# 5. 构建BLAST数据库
log "构建BLAST数据库..."
makeblastdb \
    -in proteins.fasta \
    -dbtype prot \
    -out proteins_db \
    -title "Boid Proteins Database" \
    -parse_seqids \
    -hash_index \
    -logfile makeblastdb.log

if [ $? -ne 0 ]; then
    error_exit "BLAST数据库构建失败，查看 makeblastdb.log"
fi

# 6. 验证数据库
log "验证BLAST数据库..."
blastdbcmd -db proteins_db -info > db_info.txt
DB_SEQS=$(grep "sequences" db_info.txt | awk '{print $1}')
log "数据库包含 $DB_SEQS 条序列"

# 7. 清理临时文件
log "清理临时文件..."
rm -f proteins_temp.txt

# 8. 生成元数据
log "生成元数据..."
cat > metadata.json <<EOF
{
  "build_date": "$(date -Iseconds)",
  "sequence_count": $SEQ_COUNT,
  "database_type": "BLAST",
  "source_database": "$DB_NAME",
  "blast_version": "$(blastp -version | head -1 | awk '{print $2}')"
}
EOF

log "========== BLAST数据库构建完成 =========="
log "数据库位置: $BLAST_DB_DIR/proteins_db"
log "日志文件: $LOG_FILE"

